package com.psa.element;

import android.content.ContentValues;
import android.database.Cursor;
import com.google.gson.Gson;
import com.psa.tool.DBTool;

/**
 * Created by david on 2014-08-06.
 */
public class StockItem implements IJson,ISqlObject {
    public int _id = 0;
    public Merchandise merchandise = null;
    public String QTYText = "";
    public int QTY = 0;
    public int StockCode = 0;
    public String ProdDate = "";
    @Override
    public String toJson() {
        return new Gson().toJson(this);
    }

    @Override
    public int insert(DBTool dbTool) {
        ContentValues values = new ContentValues();
        values.put("MerchandiseID", merchandise.ID);
        values.put("QTY", QTY);
        values.put("StockCode", StockCode);
        values.put("ProdDate", ProdDate);
        return (int)dbTool.insert("StockItem", values);
    }

    @Override
    public int update(DBTool dbTool) {
        ContentValues values = new ContentValues();
        values.put("MerchandiseID", merchandise.ID);
        values.put("QTY", QTY);
        values.put("StockCode", StockCode);
        values.put("ProdDate", ProdDate);
        String where = "_id = ?";
        String[] value = { String.valueOf(_id) };
        return dbTool.update("StockItem", values, where, value);
    }

    @Override
    public int delete(DBTool dbTool) {
        String where = "_id = ?";
        String[] value = { String.valueOf(_id) };
        return dbTool.delete("StockItem", where, value);
    }

    @Override
    public ISqlObject full(Cursor cursor) {
        if (cursor!=null && cursor.moveToNext()) {
            StockItem stockItem = new StockItem();
            stockItem._id = cursor.getInt(0);
            stockItem.merchandise = Merchandise.getMerchandise(cursor.getString(1));
            stockItem.QTY = cursor.getInt(2);
            stockItem.StockCode = cursor.getInt(3);
            stockItem.ProdDate = cursor.getString(4);
            stockItem.setQtyText(stockItem.QTY);
            return stockItem;
        }
        return null;
    }

    @Override
    public void clear(DBTool dbTool) {
        dbTool.delete("StockItem", "_id Like ?", new String[]{"%"});
    }

    @Override
    public String getDataSql() {
        return null;
    }

    @Override
    public String getSyncMethod() {
        return "";
    }

    public void setQtyText(int qty) {
        if (this.merchandise == null) return;
        int x = qty/merchandise.Packing;
        int y = qty%merchandise.Packing;
        this.QTYText = x + "-" + y;
    }
}
